"""
Redis configuration module following SOLID principles.
"""

import redis.asyncio as redis
from typing import Optional
from .settings import get_settings


class RedisConfig:
    """Redis configuration and connection management."""
    
    def __init__(self, redis_url: str):
        self.redis_url = redis_url
        self._connection: Optional[redis.Redis] = None
    
    async def get_connection(self) -> redis.Redis:
        """Get Redis connection."""
        if self._connection is None:
            self._connection = redis.from_url(
                self.redis_url,
                encoding="utf-8",
                decode_responses=True
            )
        return self._connection
    
    async def close(self):
        """Close Redis connection."""
        if self._connection:
            await self._connection.close()
    
    async def ping(self) -> bool:
        """Check Redis connection."""
        try:
            connection = await self.get_connection()
            return await connection.ping()
        except Exception:
            return False


# Global Redis instance
settings = get_settings()
redis_client = RedisConfig(settings.redis_url)


async def get_redis() -> redis.Redis:
    """Dependency for getting Redis connection."""
    return await redis_client.get_connection()